<template>
  <a-modal title="行驶证信息-修改" width="85vw" v-model:visible="visible" unmount-on-close>
    <div class="time-issuanceDate" style="overflow-x: hidden">
      <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
        <a-alert>
          <template #icon>
            <icon-exclamation-circle-fill />
          </template>
          请上传行驶证正/副页。支持的格式：JPG、JPEG、PNG、WEBP。请保证图片内容清晰、无反光、无折痕、背景无杂物；下方需要填写的信息要求与行驶本一致。
        </a-alert>
        <div class="flex upload-wrapper">
          <div class="flex-1">
            <page-form-row>
              <page-form-item
                label="上传行驶证正页"
                size="1/3"
                field="driveImgFrontFileId"
                :rules="[
                  { required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请上传' },
                  { validator: getValidatorFn, trigger: 'change' },
                ]"
              >
                <upload-ocr ref="uploadOcrRef" v-model="form.driveImgFrontFileId" ocrType="font" @ocrClick="fontChange" v-if="isShow" />
              </page-form-item>
              <page-form-item
                label="上传行驶证副页"
                size="1/3"
                field="driveImgBackFileId"
                :rules="[
                  { required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请上传' },
                  { validator: getValidatorFn, trigger: 'change' },
                ]"
              >
                <upload-ocr ref="uploadOcrRef" v-model="form.driveImgBackFileId" ocrType="back" @ocrClick="backChange" v-if="isShow" />
              </page-form-item>
              <page-form-item
                label="车头照"
                size="1/3"
                field="carHeadFileId"
                :rules="[
                  { required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请上传' },
                  { validator: getValidatorFn, trigger: 'change' },
                ]"
              >
                <upload-ocr ref="uploadOcrRef" v-model="form.carHeadFileId" v-if="isShow" />
              </page-form-item>
              <page-form-item field="licenseNo" label="车牌号" required size="1/3">
                <i-input v-model="form.licenseNo" :max-length="10" />
              </page-form-item>
              <page-form-item field="vin" label="车架号-车辆识别代码" size="1/3">
                <i-input v-model="form.vin" />
              </page-form-item>
              <page-form-item field="licenseNoColor" label="车牌颜色" size="1/3">
                <template #extra>
                  <div class="text-red-500">注意：请选择车牌颜色！不是车身颜色</div>
                </template>

                <a-select v-model="form.licenseNoColor" placeholder="请选择">
                  <a-option v-for="item in carSyncHrhcDict.licenseNoColorList" :key="item.value" :value="item.value" :label="item.label" />
                </a-select>
              </page-form-item>
              <page-form-item
                field="engineNum"
                label="发动机号"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input v-model="form.engineNum" :max-length="30" />
              </page-form-item>

              <page-form-item
                field="brandModel"
                label="品牌车型"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input v-model="form.brandModel" :max-length="36" />
              </page-form-item>

              <page-form-item
                field="driveNatureOwner"
                label="行驶证所属人姓名"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input v-model="form.driveNatureOwner" :max-length="50" />
              </page-form-item>

              <page-form-item
                field="drivingAddress"
                label="住址"
                :rules="{
                  required: configs.hrhcEtcEnabled && configs.quantumEtcEnabled ? form.etcSource == 2 : configs.quantumEtcEnabled,
                  message: '请输入',
                }"
                size="1/3"
              >
                <i-input v-model="form.drivingAddress" :max-length="99" />
              </page-form-item>

              <page-form-item
                field="registerDate"
                label="注册日期"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请选择' }"
              >
                <i-date-picker class="w-full" v-model="form.registerDate" popup-container=".time-issuanceDate" />
              </page-form-item>
              <page-form-item
                field="issuanceDate"
                label="发证日期"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请选择' }"
              >
                <i-date-picker class="w-full" v-model="form.issuanceDate" popup-container=".time-issuanceDate" />
              </page-form-item>

              <page-form-item
                field="driverUseNature"
                label="使用性质"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请选择' }"
              >
                <i-input v-model="form.driverUseNature" placeholder="请输入" :max-length="64" />
              </page-form-item>

              <page-form-item
                field="grossMass"
                label="总质量（单位：千克）"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input-number v-model="form.grossMass" unit="千克" :precision="0" :max="999999" :min="0" />
              </page-form-item>

              <page-form-item
                field="unladenMass"
                label="整备质量（单位：千克）"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input-number v-model="form.unladenMass" unit="千克" :precision="0" :max="999999" :min="0" />
              </page-form-item>

              <page-form-item
                field="height"
                label="外廓尺寸（单位：毫米）"
                size="1/3"
                :rules="[
                  { required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' },
                  { validator: getValidatorContourSizeFn, trigger: 'change' },
                ]"
              >
                <a-input-number
                  :max="999999"
                  :min="0"
                  placeholder="请输入"
                  v-model="form.length"
                  hide-button
                  :precision="0"
                  @change="handleChangeLength"
                />
                <span style="margin: 0 4px">x</span>
                <a-input-number :max="999999" :min="0" placeholder="请输入" v-model="form.width" hide-button :precision="0" />
                <span style="margin: 0 4px">x</span>
                <a-input-number
                  :max="999999"
                  :min="0"
                  placeholder="请输入"
                  v-model="form.height"
                  hide-button
                  :precision="0"
                  @change="handleChangeLength"
                />
              </page-form-item>
              <page-form-item
                field="ac"
                label="核定载人数"
                size="1/3"
                :rules="{ required: configs.hrhcEtcEnabled || configs.quantumEtcEnabled ? true : false, message: '请输入' }"
              >
                <i-input-number v-model="form.ac" unit="人" :precision="0" />
              </page-form-item>
              <!-- 2025-1-20补充 -->
              <page-form-item
                field="driverCarType"
                label="车辆类型"
                size="1/3"
                :rules="{
                  required: configs.hrhcEtcEnabled && configs.quantumEtcEnabled ? form.etcSource == 2 : configs.quantumEtcEnabled,
                  message: '请输入',
                }"
              >
                <a-auto-complete
                  allow-clear
                  v-model="form.driverCarType"
                  :data="
                    (carSyncHrhcDict.driverCarTypeList || []).map((item) => ({
                      ...item,
                      value: item.label,
                    }))
                  "
                  placeholder="请输入"
                  :max-length="99"
                />
              </page-form-item>
              <!-- 如果开通服务大于1家时，修改页面最后位置增加字段【选择ETC服务商】，必选 -->
              <page-form-item field="etcSource" label="选择ETC服务商" size="1/3" v-if="configs.hrhcEtcEnabled && configs.quantumEtcEnabled">
                <a-select v-model="form.etcSource" placeholder="请选择" popup-container=".time-issuanceDate">
                  <a-option v-for="item in carSyncHrhcDict.etcSourceEnums" :key="item.value" :value="item.value" :label="item.label" />
                </a-select>
              </page-form-item>
            </page-form-row>
          </div>
        </div>
      </page-form>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" :loading="okLoading" @click="submitFn"> {{ form.nextId ? '确认提交，并处理下一辆' : '确定' }} </a-button>
    </template>
  </a-modal>
</template>

<script setup name="CarInfoForm">
  import { ref, provide } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import { getCarDetail } from '@/api/asset/car.js'
  import { getHrhCmodifySync, getBatchUpdate } from '@/api/asset/equipment'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  userStore.setEpDetail()

  const visible = ref(false)
  const formRef = ref()
  const okLoading = ref(false)
  const isShow = ref(true) // 批量操作，清理图片缓存，
  const emits = defineEmits(['ok'])

  let form = ref({})
  // 商户配置
  let configs = ref({
    hrhcEtcEnabled: '',
    quantumEtcEnabled: '',
  })
  // 单条/批量
  const ways = ref('')

  const show = (e, config, way) => {
    console.log(e)
    console.log(config)
    console.log(way)
    configs.value = config
    ways.value = way
    visible.value = true
    getCarDetailFn({ id: e })
  }

  // 行驶证/车头照
  const getValidatorFn = () => {
    return (value, callback) => {
      if (!value) {
        callback('请上传')
      } else {
        callback()
      }
    }
  }

  // 外廓尺寸验证
  const getValidatorContourSizeFn = (value, callback) => {
    console.log(value)
    return new Promise((resolve) => {
      if ((!form.value.length || !form.value.width || !form.value.height) && configs.value.hrhcEtcEnabled) {
        callback('请输入')
      }
      resolve()
    })
  }

  const handleChangeLength = () => {
    formRef.value.validateField(['height'])
  }

  // 获取车辆详情
  const getCarDetailFn = (id) => {
    let fetch = getCarDetail
    if (ways.value == 'batch') {
      // 批量-详情
      fetch = getBatchUpdate
    }
    fetch(id).then((res) => {
      const {
        id,
        nextId,
        driveImgFrontFileId,
        driveImgBackFileId,
        carHeadFileId,
        licenseNo,
        vin,
        licenseNoColor,
        engineNum,
        brandModel,
        grossMass,
        unladenMass,
        registerDate,
        issuanceDate,
        driveNatureOwner,
        driverUseNature,
        length,
        width,
        height,
        ac,
        etcSource,
        drivingAddress,
        driverCarType,
      } = res.result
      form.value = {
        id,
        nextId,
        driveImgFrontFileId,
        driveImgBackFileId,
        carHeadFileId,
        licenseNo,
        vin,
        licenseNoColor,
        engineNum,
        brandModel,
        grossMass,
        unladenMass,
        registerDate,
        issuanceDate,
        driveNatureOwner,
        driverUseNature,
        length,
        width,
        height,
        ac,
        etcSource,
        drivingAddress,
        driverCarType,
      }
      if (ways.value == 'batch') {
        // 批量操作，清理图片缓存，
        setTimeout(() => {
          isShow.value = true
        }, 500)
      }
    })
  }

  const rules = {
    licenseNo: { required: true, message: '请输入' },
    vin: { required: true, message: '请输入' },
    licenseNoColor: { required: true, message: '请选择' },
    etcSource: { required: true, message: '请选择' },
  }
  const carSyncHrhcDict = usePageDict('carSyncHrhcDict')
  provide('dict', carSyncHrhcDict)
  provide('form', form)

  // 提交
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        console.log(param)
        okLoading.value = true
        getCmodifyFn(param)
      }
    })
  }
  // 修改提交
  const getCmodifyFn = (param) => {
    getHrhCmodifySync(param)
      .then((res) => {
        Message.success(res.message)
        if (form.value.nextId) {
          getCarDetailFn({ id: form.value.nextId })
          isShow.value = false
        } else {
          emits('ok')
          close()
        }
      })
      .finally(() => {
        okLoading.value = false
      })
  }
  // 驾驶证正页
  const fontChange = (e) => {
    console.log('e', e)
    if (e) {
      let forntArr = [
        'plateNum',
        'owner',
        'model',
        'vin',
        'issueDate',
        'engineNum',
        'registerDate',
        'useCharacter',
        'vehicleType',
        'address',
      ]
      form.value.licenseNo = form.value.licenseNo || e.plateNum
      form.value.vin = form.value.vin || e.vin
      form.value.engineNum = form.value.engineNum || e.engineNum
      form.value.driverUseNature = form.value.driverUseNature || e.useCharacter
      form.value.brandModel = form.value.brandModel || e.model
      form.value.driveNatureOwner = form.value.driveNatureOwner || e.owner
      form.value.driverCarType = form.value.driverCarType || e.vehicleType
      form.value.drivingAddress = form.value.drivingAddress || e.address
      if (e.registerDate) {
        form.value.registerDate = form.value.registerDate || dayjs(e.registerDate.toString()).format('YYYY-MM-DD')
      }
      if (e.issueDate) {
        form.value.issuanceDate = form.value.issuanceDate || dayjs(e.issueDate.toString()).format('YYYY-MM-DD')
      }
      forntArr.some((item) => [undefined, null, ''].includes(e[item]))
        ? Message.warning(`未全部识别，行驶证正面图片可能不够清晰`)
        : Message.success(`图片识别完毕`)
      formRef.value.clearValidate()
    }
  }
  // 驾驶证副页
  const backChange = (e) => {
    console.log('e', e)
    if (e) {
      let backArr = ['appprovedPassengerCapacity', 'grossMass', 'unladenMass', 'length', 'width', 'height']
      let newObj = Object.assign({}, e, {
        length: e.overallDimension?.length,
        width: e.overallDimension?.width,
        height: e.overallDimension?.height,
      })
      form.value.ac = form.value.ac || e.appprovedPassengerCapacity
      form.value.length = form.value.length || e.overallDimension?.length
      form.value.width = form.value.width || e.overallDimension?.width
      form.value.height = form.value.height || e.overallDimension?.height
      const grossMass = e.grossMass && e.grossMass.slice(0, -2)
      form.value.grossMass = form.value.grossMass || (grossMass ? +grossMass : '')
      const unladenMass = e.unladenMass && e.unladenMass.slice(0, -2)
      form.value.unladenMass = form.value.unladenMass || (unladenMass ? +unladenMass : '')
      backArr.some((item) => [undefined, null, ''].includes(newObj[item]))
        ? Message.warning(`未全部识别，副页图片可能不够清晰`)
        : Message.success(`图片识别完毕`)
      formRef.value.clearValidate()
    }
  }

  // 关闭
  const close = () => {
    form.value = {}
    visible.value = false
  }

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  :deep(.arco-card-header) {
    padding-bottom: 0 !important;
    height: 0 !important;
  }
  :deep(.arco-picker-container) {
    margin-top: 30px;
    margin-left: 20px;
  }

  .upload-wrapper {
    padding: 20px 20px 0 20px;
  }
</style>
